package master;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author chenyw
 * @date 2022/7/24 17:59
 */
public class M40combinationSum2 {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        //排序，便于剪枝
        Arrays.sort(candidates);
        dfs(candidates, new ArrayList<Integer>(), target, 0, 0);
        return res;

    }

    private void dfs(int[] candidates, ArrayList<Integer> list, int target, int sum, int start) {
        if (sum == target) {
            res.add(new ArrayList<Integer>(list));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            //剪枝
            if (i > start && candidates[i] == candidates[i - 1]) {
                continue;
            }
            //继续剪枝
            if (target - sum < candidates[i]) {
                break;
            }
            sum += candidates[i];
            list.add(candidates[i]);
            dfs(candidates, list, target, sum, i + 1);
            sum -= candidates[i];
            list.remove(list.size() - 1);
        }
    }

}
